package com.codingvip.tree.visit;

import com.codingvip.tree.TreeNode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
import java.util.function.Consumer;

/**
 * @author hansongtao
 */
public class TreeVisit {

    public static void main(String[] args) {
        List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5);
        TreeNode treeNode = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        treeNode.left = node2;
        treeNode.right = node3;

        node2.left = node4;
        node2.right = node5;
//        node3.left = node2;
        List<Integer> result = middleVisit2(treeNode);
        for (Integer integer : result) {
            System.out.println(integer);

        }

//        TreeNode root = null;
//        TreeNode current = null;
//        for (int i = 0; i < nums.size() / 2; i++) {
//            if (root == null) {
//                root = new TreeNode(nums.get(i));
//                current = root;
//            }
//
//            current.left=new TreeNode(nums.get(2*i+1));
//            current.right = new TreeNode(nums.get(2*i+2));
//
//
//        }


    }

    public static List<Integer> middleVisit(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;

        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode tempNode = null;
        while (root != null || !stack.isEmpty()) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            } else {
                tempNode = stack.pop();
                result.add(tempNode.val);
                root = tempNode.right;

            }
        }
        return result;
    }

    public static List<Integer> middleVisit2(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;

        }
        mVisit(root, result);
        return result;
    }

    public static void mVisit(TreeNode root, List<Integer> result) {
        if (root == null) {
            return;
        }
        mVisit(root.left, result);
        result.add(root.val);
        mVisit(root.right, result);
    }

}
